package com.wyix;

import com.wyix.entity.Order;
import com.wyix.entity.Product;
import com.wyix.error.BusinessException;
import com.wyix.error.RetryableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

/**
 * @author wangdx
 * @since 2025/8/1
 */
public class OrderPaymentSystem {
    private static final Logger log = LoggerFactory.getLogger(OrderPaymentSystem.class); // 创建日志实例

    private List<Product> products = new ArrayList<>();

    // 创建订单
    public Order createOrder(String userId, List<String> productIds, int amount) throws IOException {
        // 1. 用Objects.requireNonNull检查核心参数（Java 7+）
        Objects.requireNonNull(userId, "用户ID不能为空");
        Objects.requireNonNull(productIds, "商品ID列表不能为空");
        if (productIds.isEmpty()) {
            throw new IllegalArgumentException("商品ID列表不能为空");
        }

        // 2. 校验金额合法性
        if (amount <= 0) {
            throw new IllegalArgumentException("订单金额必须为正数：" + amount);
        }

        // 3. 检查库存（后续改造）
        if (!checkStock(productIds)) {
            throw new BusinessException("PRODUCT_OUT_OF_STOCK", "商品库存不足");
        }

//        // 1. 检查库存
//        if (!checkStock(productIds)) {
//            System.out.println("库存不足");
//            return null;
//        }



        // 2. 创建订单对象
        Order order = new Order();
        order.setOrderId(UUID.randomUUID().toString());
        order.setUserId(userId);
        order.setProductIds(productIds);
        order.setAmount(amount);

        // 3. 调用支付接口
        String paymentResult = callPaymentGateway(order.getOrderId(), amount);
        order.setStatus(paymentResult.equals("SUCCESS") ? "PAID" : "FAILED");

        return order;
    }

    // 检查库存
    private boolean checkStock(List<String> productIds) throws IOException {
        // 从文件读取库存数据（模拟）
        Map<String, Integer> stockMap = readStockFromFile("stock.txt");
        for (String id : productIds) {
            if (stockMap.get(id) <= 0) { // 危险操作！
                return false;
            }
        }
        return true;
    }

    // 调用支付网关（模拟网络请求）
    private String callPaymentGateway(String orderId, int amount) {
        // 模拟网络延迟
        try { Thread.sleep(100); } catch (InterruptedException e) {}

        // 随机模拟支付失败
        if (new Random().nextInt(5) == 0) {
            throw new RuntimeException("支付超时"); // 危险！直接抛出未处理异常
        }
        return "SUCCESS";
    }

    // 从文件读取库存
    private Map<String, Integer> readStockFromFile(String path) throws IOException {
//        Map<String, Integer> stock = new HashMap<>();
//        BufferedReader reader = new BufferedReader(new FileReader(path)); // 危险！未处理异常
//        String line;
//        while ((line = reader.readLine()) != null) { // 危险！可能NPE
//            String[] parts = line.split(":");
//            stock.put(parts[0], Integer.parseInt(parts[1])); // 危险！可能NumberFormatException
//        }
//        reader.close(); // 危险！流未关闭
//        return stock;
        Map<String, Integer> stock = new HashMap<>();

        // 使用try-with-resources自动关闭流（Java 7+）
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            int lineNum = 1;
            while ((line = reader.readLine()) != null) {
                lineNum++;
                String[] parts = line.split(":");
                // 校验数据格式
                if (parts.length != 2) {
                    log.warn("库存文件第{}行格式错误，跳过：{}", lineNum, line);
                    continue;
                }
                // 安全转换数字
                try {
                    int stockNum = Integer.parseInt(parts[1]);
                    stock.put(parts[0], stockNum);
                } catch (NumberFormatException e) {
                    log.error("库存文件第{}行数字格式错误：{}", lineNum, parts[1]);
                }
            }
        } catch (FileNotFoundException e) {
            // 转换为业务异常并记录日志
            throw new BusinessException("FILE_NOT_FOUND", "库存文件不存在：" + path, e);
        } catch (IOException e) {
            throw new RetryableException("FILE_READ_ERROR", "库存文件读取失败，可重试", e);
        }

        return stock;
    }

    public static void main(String[] args) throws IOException {
        log.info("开始启动订单支付系统");
        OrderPaymentSystem system = new OrderPaymentSystem();
        // 测试创建订单（故意传入问题参数）
        List<String> productIds = Arrays.asList("P001", "P002");
        Order order = system.createOrder(null, productIds, -100); // 用户ID为null，金额为负数
        System.out.println("创建订单成功：" + order.getOrderId()); // 危险！order可能为null
    }
}